from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework.mixins import RetrieveModelMixin
from .models import GoodsShelf
from .serializer import GoodsSerializer, GoodsDetailSerializer
from utils.view import CommonListModelMixin, CommonRetrieveModelMixin
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from django.conf import settings
from utils.response import APIResponse
from rest_framework.exceptions import APIException


class GoodsView(GenericViewSet, CommonListModelMixin):
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[0:settings.HOME_COUNT]
    serializer_class = GoodsSerializer


class TopGoodsView(GenericViewSet, CommonListModelMixin):
    serializer_class = GoodsSerializer
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True).order_by('-sales_num')[
               0:settings.HOME_COUNT]


class TimeView(GenericViewSet, CommonListModelMixin):
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True).order_by('-created_time')[
               0:settings.HOME_COUNT]
    serializer_class = GoodsSerializer


class GoodsDetailView(GenericViewSet, CommonRetrieveModelMixin):
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True)
    serializer_class = GoodsDetailSerializer


class GoodsSearchView(GenericViewSet, CommonListModelMixin):
    filter_backends = [SearchFilter]
    search_fields = ['goods_name', 'selling_price']
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = GoodsSerializer


class GoodsCategoryView(GenericViewSet, CommonListModelMixin):
    queryset = GoodsShelf.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = GoodsSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['goods_classify_id']


class GoodsOneView(GenericViewSet, RetrieveModelMixin):
    queryset = GoodsShelf.objects.all()

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        goods_obj = GoodsShelf.objects.filter(id=instance.id).first()
        if goods_obj.stock_num <= 0:
            raise APIException('库存告急,请联系管理员')
        return APIResponse()
